<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
      layout:decorator="layout">
<head>
  <meta charset="UTF-8">
  <title th:text="${title}"></title>
</head>
<body>
<!-- Begin Page Content -->
<div class="container-fluid mt-4" layout:fragment="content">
  <div class="card shadow mb-4">
    <div class="card-header py-3">
      <h6 class="m-0 font-weight-bold text-primary">
        搜索&添加
        <span id="operators_pack_btn" style="cursor: pointer"><i class="fas fa-angle-up"></i></span>
      </h6>
    </div>
    <div class="card-body" id="operators_panel">
      <!--<div id="operators_panel">-->
      <div class="row">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12 form-group">
          <label for="username">用户名</label>
          <input type="text" class="form-control" id="username" placeholder="username">
        </div>

        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12 form-group">
          <label for="realname">真实姓名</label>
          <input type="text" class="form-control" id="realname" placeholder="realname">
        </div>
      </div>
      <div class="row">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12 form-group">
          <label for="rid">角色权限</label>
          <select class="form-control" id="rid">
            <option value="-1">全部</option>
            <option th:each="roleInfo:${rolelist}" th:value="${roleInfo.id}" th:text="${roleInfo.description}"></option>
          </select>
        </div>
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 form-group">
          <button type="button" class="btn btn-secondary btn-block btn-bottom" id="add">新增</button>
        </div>
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 form-group">
          <button type="button" class="btn btn-primary btn-block btn-bottom" id="searchBt">搜索</button>
        </div>
      </div>
    </div>
  </div>

  <!--数据-->
  <!-- DataTales Example -->
  <div class="card shadow mb-4">
    <div class="card-header py-3">
      <h6 class="m-0 font-weight-bold text-primary">
        数据
        <!--<a href="#" style="float:right;font-weight: normal;">下载</a>-->
        <button type="button" class="btn btn-link" style="float:right;font-weight: normal;display: none;">下载</button>
      </h6>

    </div>
    <div class="card-body">
      <div class="table-responsive" id="data">
      </div>
    </div>
  </div>


  <div class="modal fade" id="getExamine" tabindex="-1" role="dialog" aria-labelledby="menu_examine_lable"  aria-hidden="true" style="z-index: 1051;overflow:auto;overflow-y:scroll;">
    <div class="modal-dialog" style="z-index: 1051">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title" id="menu_examine_lable">用户编辑</h4>
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        </div>
        <div class="modal-body">
          <div class="menuClasify-detailed" data-id='' data-restaurantId="">
            <form class="form-horizontal">
              <input id="postUrl" type="hidden"/>
              <input id="type" type="hidden"/>
              <div id="id-group" class="form-group">
                <label class="control-label">id：</label>
                <input readonly="true" type="text" class="form-control" id="id" placeholder="" role="button" data-toggle="popover" data-placement="bottom" data-trigger="focus" data-content="">
              </div>
              <!--<input id="id" name="id" type="hidden"/>-->
              <div class="form-group">
                <label class="control-label">用户名：</label>
                <input type="text" class="form-control" id="username_edit" placeholder="" role="button" data-toggle="popover" data-placement="bottom" data-trigger="focus" data-content="">
              </div>
              <div class="form-group">
                <label class="control-label">真实姓名：</label>
                <input type="text" class="form-control" id="realName_edit" placeholder="" role="button" data-toggle="popover" data-placement="bottom" data-trigger="focus" data-content="">
              </div>

              <div class="form-group">
                <label class="control-label">密码：</label>
                <input type="password" class="form-control" id="passwd_edit" placeholder="" role="button" data-toggle="popover" data-placement="bottom" data-trigger="focus"/>
              </div>
              <div class="form-group">
                <label class="control-label">确认密码：</label>
                <input type="password" class="form-control" id="repasswd_edit" placeholder="" role="button" data-toggle="popover" data-placement="bottom" data-trigger="focus"/>
              </div>
<!--              <div class="form-group" sec:authorize="hasAnyAuthority('A_Develop_Role')">-->
              <div class="form-group">
                <label class="control-label">角色：</label>
                <select class="form-control" id="roleSelect" multiple="multiple" style="min-height: 100px;">
                  <option th:each="roleInfo:${rolelist}" th:value="${roleInfo.id}" th:text="${roleInfo.description}"></option>
                </select>
              </div>

              <div class="form-group">
                <label class="control-label">首页：</label>
                <input type="text" class="form-control input-change" id="defaultUrl_edit" placeholder="" role="button" data-toggle="popover" data-placement="bottom" data-trigger="focus" data-content="">
              </div>

              <div class="form-group">
                <label class="control-label">邮箱：</label>
                <input type="text" class="form-control" id="email_edit" placeholder="" role="button" data-toggle="popover" data-placement="bottom" data-trigger="focus" data-content="">
              </div>
              <div class="form-group">
                <label class="control-label">手机号：</label>
                <input type="text" class="form-control" id="mobilePhone_edit" placeholder="" role="button" data-toggle="popover" data-placement="bottom" data-trigger="focus" data-content="">
              </div>
              <div class="form-group">
                <label class="control-label">状态：</label>
                <select class="form-control" id="status_edit">
                  <option th:each="userStatus:${userStatusList}" th:value="${userStatus.code}" th:text="${userStatus.description}"</option>
                </select>
              </div>
            </form>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary preserve-btn" id="save">保存</button>
        </div>
      </div>
    </div>
  </div>

  <ul style="display: none">
    <li name="manageMenuLi" th:each="manageMenuVo:${manageMenuVoList}" th:value="${manageMenuVo.menuUrl}" th:text="${manageMenuVo.getMenuName()}"></li>
  </ul>

</div>

<th:block layout:fragment="js">
  <script type="text/javascript">

      var defaultUrls = new Array();
      //用户首页
      // defaultUrls.push({"value":"/system/shop/shopInfo/list","text":"商户管理：/system/shop/shopInfo/list"});
      defaultUrls.push({"value":"/system/logger/list","text":"操作日志：/system/logger/list"});
      defaultUrls.push({"value":"/system/manager/list","text":"用户管理：/system/manager/list"});
      defaultUrls.push({"value":"/system/role/list","text":"角色管理：/system/role/list"});
      // defaultUrls.push({"value":"/system/auth/list","text":"权限管理：/system/auth/list"});

      var userStatusMap={};
      $("#status_edit option").each(function () {
          userStatusMap[$(this).val()]=$(this).text()
      })
      // <c:forEach items="${userStatusList}" var="userStatus">
      // userStatusMap[${userStatus.code}] = '${userStatus.description}';
      // </c:forEach>
      // var defaultRole="";
      // <c:forEach var="role" items="${rolelist}">
      //     <c:if test="${role.rolename=='R_Default'}">
      // defaultRole="${role.id}"
      //     </c:if>
      //     </c:forEach>

          // $(function(){
          //
          //
          // });
      function getDefaultUrlText(defaultUrl){
          for(var i=0;i<defaultUrls.length;i++){
              //console.info("defaultUrls[i].value->"+defaultUrls[i].value);
              if(defaultUrls[i].value==defaultUrl){
                  return defaultUrls[i].text;
              }
          }
          return defaultUrl;
      }


      $(function () {
          $("li[name='manageMenuLi']").each(function () {
            var v=$(this).attr("value")
            var t=$(this).text()
            defaultUrls.push({"value":v,"text":t+"："+v});
          });

          $("#operators_pack_btn").click(function () {
              if ($("#operators_panel").is(":hidden")) {
                  $("#operators_panel").show(100);
                  $(this).html("<i class=\"fas fa-angle-up\"></i>");
              } else {
                  $("#operators_panel").hide(100);
                  $(this).html("<i class=\"fas fa-angle-down\"></i>");
              }
          });

          $("#searchBt").click(function () {
              search();
          });
          search();
      });

      function search(){
          var data={
              username:$("#username").val(),
              rid:$("#rid").val(),
              realname: $("#realname").val(),
              _csrf:csrfToken
//        page:$("#page").val(),
//        max:10
          };
          $("#data").datagrid("load",{
              url:"[[@{/}]]system/manager/listSearch",
              data:data,
              showDetail:true,
              colResizeEnable:true,
              fields:[
                  {name:"id",autoHidden:true,text:"ID",inTable:false},
                  {name:"username",autoHidden:false,text:"用户名",inTable:true},
                  {name:"realName",autoHidden:false,text:"真实姓名",inTable:true},
                  {name:"email",autoHidden:false,text:"邮箱",inTable:false},
                  {name:"mobilePhone",autoHidden:false,text:"手机号",inTable:false},
                  {name:"status",autoHidden:true,text:"状态",inTable:true,render:function(row){
                          return userStatusMap[row.status];
                      }},
                  {name:"lastLoginTime",autoHidden:false,text:"最后登录时间",inTable:false},
                  {name:"roleInfoList",autoHidden:true,text:"角色",inTable:true,render:function(row){
                          if(row.roleInfoList != null&&row.roleInfoList.length>0) {
                              var temp="";
                              for(var i=0;i<row.roleInfoList.length;i++){
                                  temp+=row.roleInfoList[i].description+"&nbsp;&nbsp;";
                              }
                              return temp;
                          }else{
                              return "";
                          }
                      }
                  },
                  {name:"defaultUrl",autoHidden:true,text:"首页",inTable:true,render:function(row){
                          if(row.defaultUrl==null){
                              return "";
                          }else{
                              //console.info("ddd->"+getDefaultUrlText(row.defaultUrl));
                              return getDefaultUrlText(row.defaultUrl);
                          }
                      }}
              ],
              dialogTitle:"用户详情",
              operations:[

                  {name:"edit",text:"编辑",handler:function(row){
                          $("#id").val(row.id);
                          $("#menu_examine_lable").text("用户编辑");
                          $("#postUrl").val("[[@{/}]]system/manager/save");
                          $("#type").val("modify");
                          $("#id-group").show();
                          $("#username_edit").val(row.username);
                          $("#realName_edit").val(row.realName);
                          $("#passwd_edit").val("");
                          $("#repasswd_edit").val("");
                          var temp="";
                          for(var i=0;i<row.roleInfoList.length;i++){
                              temp+="["+row.roleInfoList[i].id+"]";
                          }
                          if(document.getElementById("roleSelect")!=null) {
                            var all_options = document.getElementById("roleSelect").options;
                            for (i = 0; i < all_options.length; i++) {
                              all_options[i].selected = false;
                              if (temp.indexOf("[" + all_options[i].value + "]") != -1) // 根据option标签的ID来进行判断 测试的代码这里是两个等号
                              {
                                all_options[i].selected = true;
                              }
                            }
                          }
                          $("#defaultUrl_edit").val(row.defaultUrl);
                          $("#email_edit").val(row.email);
                          $("#mobilePhone_edit").val(row.mobilePhone);
                          //$("#status_edit").val(row.status);
                          all_options = document.getElementById("status_edit").options;
                          for (i=0; i<all_options.length; i++){
                              all_options[i].selected = false;
                              if (all_options[i].value == row.status)
                              {
                                  all_options[i].selected = true;
                              }
                          }

                          $("#getExamine").modal("show");
                      }},
                  {name:"remove",text:"删除",handler:function(row){
                          var pp=prompt("确定要删除【"+row.username+"】吗？请输入‘确定’","");
                          if(pp != null){
                              if(pp=="确定"){
                                  del(row.id);
                              }else{
                                  alert("输入错误！");
                              }
                          }
                      }}
              ],
              webContext:'[[@{/}]]'
          });
      }

      function del(id){

          $.doSubmit({
              submitUrl:"[[@{/}]]system/manager/delUser",
              data:{userId:id,
                  _csrf:csrfToken},
              type:"post",
              callBack:function(response){
                  if(response == "ok"){
                      search()
                  }else{
                      alert(response);
                  }
              },
              webContext:'[[@{/}]]'
          });
      }

      $(function(){
          $("#add").click(function () {
              $("#menu_examine_lable").text("用户增加");
              $("#postUrl").val("[[@{/}]]system/manager/addUser");
              $("#type").val("add");
              $("#id").val("-1");
              $("#id-group").hide();
              $("#username_edit").val("");
              $("#realName_edit").val("");
              $("#passwd_edit").val("");
              $("#repasswd_edit").val("");
              $("#roleSelect").val("");
              $("#defaultUrl_edit").val("");
              // $("#unitInfoList").html("");
              $("#email_edit").val("");
              $("#mobilePhone_edit").val("");
              $("#status_edit").val("0");
              $("#getExamine").modal("show");
          });

      });

      var unitList;
      $(function(){
          $("#save").click(function(){
              var url = $("#postUrl").val();
              var id=$("#id").val();
              var username=$("#username_edit").val();
              var realName=$("#realName_edit").val();
              var passwd=$("#passwd_edit").val();
              var repasswd=$("#repasswd_edit").val();
              var formType=$("#type").val();
              console.info(formType);
              var ridList=null;
              // if(formType=="add"){
              //     ridList=defaultRole;
              // }
              var roleSelect=$("#roleSelect").val();
              ridList="";
              if(roleSelect!=null&&roleSelect.length>0){
                  for(var i=0;i<roleSelect.length;i++) {
                      ridList+=roleSelect[i]+"#";
                  }
              }
              console.log("roleSelect:"+roleSelect);
              var defaultUrl=$("#defaultUrl_edit").val();
              // var unitList=null;
              // if(formType=="add"){
              //     unitList="";
              // }
              // unitList="";
              // if($("#unitInfoList option").length>0) {
              //     for(i=0;i<$("#unitInfoList option").length;i++) {
              //         unitList+=$($("#unitInfoList option")[i]).val()+"#";
              //     }
              // }
              var email=$("#email_edit").val();
              var mobilePhone=$("#mobilePhone_edit").val();
              var status=$("#status_edit").val();
              var requestData={
                  id:id,
                  username:username,
                  realName:realName,
                  passwd:passwd,
                  repasswd:repasswd,
                  defaultUrl:defaultUrl,
                  email:email,
                  mobilePhone:mobilePhone,
                  status:status,
                  _csrf:csrfToken
              };
              if(ridList!=null){
                  requestData["ridListStr"]=ridList;
              }
              // if(unitList!=null){
              //     requestData["unitList"]=unitList;
              // }
              $.doSubmit({
                  type: "POST",
                  submitUrl: url,
                  data: requestData,
                  //beforeSend: validateData,
                  callBack: function(response){
                      var data= $.parseJSON(response);
                      if(!data.ok)
                          alert(data.msg);
                      else {
                          //search();
                          $("#data").datagrid("reload");
                          $("#getExamine").modal("hide");
                      }
                  },
                  webContext:'[[@{/}]]'
              });
          });
      });

      // $(function(){
      //     $("#remove").click(function () {
      //         $("#unitInfoList option:selected").remove();
      //     });
      //     $("#unitSelect").click(function(){
      //         unitList = $("#unitInfoList option");
      //         $("#unitSelectListIframe")[0].contentWindow.getSelect(unitList);
      //         $("#unitSelectList").modal("show");
      //     });
      //     $("#submitUnit").click(function(){
      //         var units = $("#unitSelectListIframe")[0].contentWindow.saveUnit();
      //         for(var i=0;i<units.length;i++){
      //             selectUnits(units[i].id,units[i].name);
      //         }
      //         $("#unitSelectList").modal("hide");
      //
      //     });
      // });


      function hasAuth(id){
          var as=$("#auths option");
          for(i=0;i<as.length;i++){
              if($(as[i]).val()==id) {
                  return true;
              }
          }
          return false;
      }

      // function selectUnits(id,name){
      //     var as=$("#unitInfoList option");
      //     for(i=0;i<as.length;i++){
      //         if($(as[i]).val()==id) {
      //             return;
      //         }
      //     }
      //     $("#unitInfoList").append("<option value='"+id+"'>"+name+"</option>")
      // }
      // function removeUnit(id){
      //     var as=$("#unitInfoList option");
      //     for(i=0;i<as.length;i++){
      //         if($(as[i]).val()==id) {
      //             as[i].remove();
      //             return;
      //         }
      //     }
      // }


      $(function(){
        $(".input-change").focus(function() {
          console.info("ddd")
          //先拼接字符串
          var str = $(this).val();
          var obj = "#" + $(this).attr("id");
          if (str == "" || str == null || str == undefined) {
            //全查询
            getCandidate(obj, defaultUrls,str);
          } else {
            //关键字查询
            getCandidate(obj, defaultUrls,str);
          }
          var inputWidth = $(this).width() + 40;
          $(this).siblings(".input-candidate").width(inputWidth).show().find("li");
        });

        $(".input-change").keyup(function() {
          getCandidate("#" + $(this).attr("id"),defaultUrls,$(this).val());
          var inputWidth = $(this).width() + 40;
          $(this).siblings(".input-candidate").width(inputWidth).show().find("li");
        });

        $(".input-change").blur(function() {
          $(this).siblings(".input-candidate").hide();
        });

        //获取所有候选，拼接字符串
        function getCandidate(obj, data,searchStr) {
          var str = "<ul class='input-candidate'>";
          for (var i = 0; i < data.length; i++) {
            if(searchStr == "" || data[i].value.indexOf(searchStr) != -1) {
              str += "<li><p>" + data[i].text + "</p><input type='hidden' value='"+data[i].value+"'></li>";
            }
          }
          str += "</ul>";
          $(obj).siblings(".input-candidate").remove();
          $(obj).parent().append(str).find("li").unbind().on("mousedown", function() {
            $(obj).val($(this).find("input").val());
          });
        }
      });

  </script>
</th:block>
</body>
</html>